package com.bdsoft.security.service;

import com.bdsoft.security.mapper.LoginMapper;
import com.bdsoft.security.entity.SecurityUser;
import com.bdsoft.security.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final LoginMapper loginMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String USER_AUTH_CACHE_PREFIX = "user:auth:";


    @Autowired
    public CustomUserDetailsService(LoginMapper loginMapper, RedisTemplate<String, Object> redisTemplate) {
        this.loginMapper = loginMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!StringUtils.hasText(username)) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        String cacheKey = USER_AUTH_CACHE_PREFIX + username.trim();

        // 1. 先查Redis缓存
        SecurityUser cachedUser = null;
        try {
            Object obj = redisTemplate.opsForValue().get(cacheKey);
            if (obj instanceof SecurityUser) {
                cachedUser = (SecurityUser) obj;
            }
        } catch (Exception e) {
            System.out.println("Redis反序列化异常: " + e.getMessage());
        }
        if (cachedUser != null) {
            return cachedUser;
        }

        // 2. 缓存未命中则查数据库
        User user = loginMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        // 3. 查询用户角色和权限
        List<Map<String, Object>> roles = getUserRoles(user.getId());
        List<String> resourceIds = loginMapper.getResourceIdsByUserId(user.getId());
        SecurityUser userDetails = new SecurityUser(user, resourceIds, roles);

        // 4. 存入Redis（30分钟过期）
        try {
            redisTemplate.opsForValue().set(cacheKey, userDetails, 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            System.out.println(e);
        }
        return userDetails;
    }
    public void evictUserCache(String username) {
        String cacheKey = USER_AUTH_CACHE_PREFIX + username.trim();
        redisTemplate.delete(cacheKey);
    }
    /**
     * 根据用户ID获取角色信息
     * @param userId 用户ID（String类型）
     * @return 角色列表
     */
    private List<Map<String, Object>> getUserRoles(String userId) {
        try {
            List<Map<String, Object>> roles = loginMapper.selectUserRole(userId);
            return roles != null ? roles : Collections.emptyList();
        } catch (Exception e) {
            // 记录错误日志
            // log.error("获取用户角色失败，用户ID: {}", userId, e);
            return Collections.emptyList();
        }
    }

//    /**
//     * 根据用户ID加载用户信息
//     * @param userId 用户ID（String类型）
//     * @return UserDetails
//     * @throws UsernameNotFoundException 用户不存在时抛出
//     */
//    public UserDetails loadUserById(String userId) throws UsernameNotFoundException {
//        if (!StringUtils.hasText(userId)) {
//            throw new IllegalArgumentException("用户ID不能为空");
//        }
//
//        User user = loginMapper.selectById(userId.trim());
//        if (user == null) {
//            throw new UsernameNotFoundException("用户不存在");
//        }
//
//        List<String> resourceIds = loginMapper.getResourceIdsByUserId(userId);
//        return new SecurityUser(user, resourceIds);
//    }
} 